package com.example.remote.server;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * @Description : 模拟浏览器发送博客园闪存
 * @Author : Bruce Lee
 * @CreateTime : 2024/2/22
 */

@Slf4j
@Service
public class RemoteServer {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${mock.content}")
    private String content;

    @Value("${mock.Cookie}")
    private String Cookie;

    // 每隔10分钟执行一次
    @Scheduled(fixedRate = 600000)
    public void getRemoteData() {
        String url = "https://ing.cnblogs.com/ajax/ing/Publish";
        String time = new Date().toString();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cookie", Cookie);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 计算距离下班还有多少分钟(默认17：30下班)
        long between = ChronoUnit.MINUTES.between(LocalTime.now(), LocalTime.of(17, 30));

        // 表单数据
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("content", "当前北京标准时间：" + time + " 距离下班还有" + between + "分钟 " + content);
        params.add("publicFlag", "1");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);

        // 发送请求
        restTemplate.postForObject(url, requestEntity, String.class);
    }
}
